package com.xzx.shop_front_api.controller;

import co.elastic.clients.elasticsearch.core.IndexRequest;
import com.xzx.shop_front_api.entity.ESNews;
import com.xzx.shop_front_api.entity.News;
import com.xzx.shop_front_api.service.NewsService;
import com.xzx.shop_front_api.utils.JsonResult;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightParameters;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;

import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.List;


@RestController
@RequestMapping("api/news")
public class EsNewsController {
    @Resource
    private ElasticsearchOperations elasticsearchOperations;

    @Autowired
    private NewsService newsService;


    // 文档添加接口
    @PostMapping("add")
    public JsonResult add(@RequestBody News news) {
        if (news.getTitle() == null || news.getContent() == null) {
            return JsonResult.failed("标题和内容不能为空");
        }
        int dbResult = newsService.addNews(news);
        if (dbResult == 0) {
            return JsonResult.failed("数据库保存失败");
        }
        // 同步到ES
        ESNews esNews = new ESNews();
        esNews.setId(news.getId());
        esNews.setTitle(news.getTitle());
        esNews.setContent(news.getContent());
        esNews.setCreateTime(news.getCreateTime());
        elasticsearchOperations.save(esNews);
        return JsonResult.success("添加成功", esNews);
    }

    // 根据id查询文档接口
    @GetMapping("getById")
    public JsonResult getById(@RequestParam("id") Long id) {
        if (id == null) {
            return JsonResult.failed("id不能为空");
        }
        ESNews esNews = elasticsearchOperations.get(id.toString(), ESNews.class);
        if (esNews == null) {
            return JsonResult.failed("文档不存在");
        }
        return JsonResult.success("查询成功", esNews);
    }

    // 根据id删除文档（含不存在提示）
    @GetMapping("delete")
    public JsonResult delete(@RequestParam("id") Long id) {
        if (id == null) {
            return JsonResult.failed("id不能为空");
        }
        ESNews esNews = elasticsearchOperations.get(id.toString(), ESNews.class);
        if (esNews == null) {
            return JsonResult.failed("文档不存在，删除失败");
        }
        elasticsearchOperations.delete(id.toString(), ESNews.class);
        int dbResult = newsService.deleteNewsById(id);
        if (dbResult == 0) {
            return JsonResult.failed("数据库删除失败");
        }
        return JsonResult.success("删除成功", null);
    }

    // 高亮搜索
    @GetMapping("highlight")
    public JsonResult highlight(@RequestParam("wd") String wd) {
        // 创建高亮配置
        HighlightField highlightField = new HighlightField("title");
        HighlightParameters parameters = HighlightParameters.builder()
                .withPreTags("<span style='color: red'>")
                .withPostTags("</span>")
                .withFragmentSize(Integer.MAX_VALUE)
                .withNumberOfFragments(1)
                .build();

        Highlight highlight = new Highlight(parameters, List.of(highlightField));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, ESNews.class);

        // 构建查询
        NativeQuery query = NativeQuery.builder()
                .withQuery(q -> q
                        .match(m -> m
                                .field("title")
                                .query(wd)
                        )
                ).withPageable(
                        PageRequest.of(0, 10,
                                Sort.by(
                                        Sort.Order.desc("createTime")
                                )
                        )
                )
                .withHighlightQuery(highlightQuery)
                .build();
        SearchHits<ESNews> searchHits = elasticsearchOperations.search(query, ESNews.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功", resultData);
    }

    @GetMapping("muli_match")
    public JsonResult muliMatch(@RequestParam("wd") String wd) {
        // 1. 构建多字段查询 + 高亮配置
        NativeQuery query = NativeQuery.builder()
                .withQuery(q -> q.multiMatch(m -> m
                        .query(wd) // 搜索关键词
                        .fields("title^3", "content") // 匹配字段，title 权重更高
                ))
                .build();

        // 2. 执行查询
        SearchHits<ESNews> hits = elasticsearchOperations.search(query, ESNews.class);
        List<ESNews> result = hits.stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());
        return JsonResult.success("ok", result);
    }
}